package com.leesche.zcsp.node.web.controller.web.v2.sms;

import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.gernerator.MobileCodeGernerator;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2017/1/5 11:36: * 创建该类并实现业务逻辑: *********
 * @Title: SmsController.java
 * @Description: TODO(Web短信Controller)
 * @date 2017/1/5 11:36
 */
@Controller
@RequestMapping(value = "/v2/sms")
public class WebSmsController {

    private static final Logger logger = Logger.getLogger(WebSmsController.class);

    @Autowired
    private SmsService smsService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PrivilegeService privilegeService;

    /**
     * @param mobile 手机号码
     * @Title: sendCodeByMobile
     * @Description: TODO(按手机号码，发送短信[用户注册])
     */
    @ResponseBody
    @RequestMapping(value = "sendcodebymoblie", method = RequestMethod.POST)
    public Map<String, Object> sendSmsCodeToMobile(String mobile, String imgcode) {
        try {
            if (!SessionManager.getSessionAttribute(Constants.LOGIN_CODE).equals(imgcode)) {
                return WebResult.failure("验证码输入错误").put("ERROR", "imgcode").toMap();
            } else if (mobile == null || "".equals(mobile)) {
                return WebResult.failure("手机号码不能为空").put("ERROR", "mobile").toMap();
            }

            SysUser user = new SysUser();
            user.setMobile(mobile);
            user = sysUserService.findUserByUsername(user);
            if (user != null) {
                return WebResult.failure("手机号码已被注册，请更换其他号码").put("ERROR", "mobile").toMap();
            } else {
                //将该手机号作为Key值
                return beginSendMsg(mobile);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param mobile 手机号码
     * @Title: sendSmsCodeToUserMobile
     * @Description: TODO(按手机号码，发送短信[ 找回密码 ])
     */
    @ResponseBody
    @RequestMapping(value = "sendfogetcode", method = RequestMethod.POST)
    public Map<String, Object> sendSmsCodeToUserMobile(String mobile, String imgcode) {
        try {
            if (!SessionManager.getSessionAttribute(Constants.LOGIN_CODE).equals(imgcode)) {
                return WebResult.failure("验证码输入错误").put("ERROR", "imgcode").toMap();
            } else if (mobile == null || "".equals(mobile)) {
                return WebResult.failure("手机号码不能为空").put("ERROR", "mobile").toMap();
            }

            SysUser user = new SysUser();
            user.setMobile(mobile);
            user = sysUserService.findUserByUsername(user);
            if (user == null) {
                return WebResult.failure("手机号码不存在,请核对").put("ERROR", "mobile").toMap();
            } else {
                //将该手机号作为Key值
                return beginSendMsg(mobile);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: sendSmsCodeToUserMobile
     * @Description: TODO(按手机号码，发送短信[ 找回密码 ])
     */
    @ResponseBody
    @RequestMapping(value = "sendcurrentuser", method = RequestMethod.POST)
    public Map<String, Object> sendSmsCodeToCurrentUser() {
        try {

            Principal principal = privilegeService.getCurrentPrincipal();
            if (principal == null) {
                return WebResult.failure("用户尚未登录").toMap();
            } else {
                QuerySysUserCondition condition = new QuerySysUserCondition();
                condition.setUserid(principal.getUserid());
                SysUserDto userdto = sysUserService.findListsByCondition(condition).get(0);
                if (userdto != null && !"".equals(userdto.getMobile())) {
                    //将该手机号作为Key值
                    return beginSendMsg(userdto.getMobile());
                } else {
                    return WebResult.failure("用户有没手机号码").toMap();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: getUserPlaces
     * @Description: TODO(验证当前用户收到的短信验证码)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "vaildcode", method = RequestMethod.GET)
    public Map<String, Object> vaildMobileCode(String mobileCode) {
        try {
            if (mobileCode == null || "".equals(mobileCode)) {
                return WebResult.failure("验证码不能为空").toMap();
            } else {
                VaildPhone validPhone = PhoneCodeCacheTimer.get(mobileCode);
                if (validPhone == null) {
                    return WebResult.failure("验证码错误,请重新输入").toMap();
                } else if (validPhone.getValidTime() < new Date().getTime()) {
                    PhoneCodeCacheTimer.remove(mobileCode);
                    return WebResult.failure("短信验证码已过期，请重新获取").toMap();
                } else {
                    Long userid = privilegeService.getCurrentPrincipal().getUserid();
                    String userMobile = sysUserService.selectByPrimaryKey(userid).getMobile();
                    if (userMobile == null || "".equals(userMobile))
                        return WebResult.failure("用户没有手机号码").toMap();
                    else if (!validPhone.getPhone().equals(userMobile)) {
                        return WebResult.failure("与获取短信的手机号码一致").toMap();
                    } else {
                        return WebResult.success().toMap();
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @param mobileNum 手机号码
     * @return 发送短信结果
     * @Title: beginSendMsg(String mobileNum, HttpSession session)
     * @Description: TODO(开始发送短信验证码)
     * @author Jerry
     * @date 2016-10-29 10:35:55
     */
    private Map<String, Object> beginSendMsg(String mobileNum) throws Exception {
        //生成随机码
        String mobileCode = MobileCodeGernerator.mobileCodeGernerator();
        //发送短信
        Message<String> smsReport = smsService.sendSMS(mobileNum, mobileCode);
        //存在到session 发送成功
        if (Message.isSuccess(smsReport.getType())) {
            //有效时间
            long validTime = new Date().getTime() + (Constants.NOTIC_DEFAULT_MOBLIE_CODE_MAXINACTIVEINTERVAL * 60000);
            //保存短信验证码
            VaildPhone vaildPhone = new VaildPhone(validTime, mobileNum);
            PhoneCodeCacheTimer.put(mobileCode, vaildPhone);
            return WebResult.success().info(mobileNum).toMap();
        } else {
            String errorMsg = smsReport.getContent();
            if ("InvalidRecNum.Malformed".equals(errorMsg)) {
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errorMsg)) {
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }

        }
    }

    /**
     * @param mobileNum 手机号码
     * @param contents  短信内容集合
     * @param templete  短信模版
     * @return
     * @Title: beginSendMsg(String mobileNum, Map<String, String> contents, String templete)
     * @Description: TODO(发送短信)
     * @author Jerry Chan
     * @date 2016/12/28 15:36
     */
    private Map<String, Object> beginSendMsg(String mobileNum, Map<String, String> contents, String templete) throws Exception {
        Message<String> smsReport = smsService.sendSMS(mobileNum, contents, templete);
        if (Message.isSuccess(smsReport.getType())) {
            return WebResult.success().info(smsReport.getContent()).toMap();
        } else {
            String errMag = smsReport.getContent();
            if ("InvalidRecNum.Malformed".equals(errMag)) {
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errMag)) {
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }
        }
    }


}
